package com.shop.controller;

import com.shop.entity.AdminUser;
import com.shop.entity.Result;
import com.shop.service.AdminService;
import com.shop.util.CaptchaUtil;
import com.shop.util.ResultUtil;
import com.shop.util.SessionUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
*@author asus11
*@create 2018/8/20 11:25
*@desc 管理员控制器
**/
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private AdminService adminService;

    /**
     * 管理员登陆页面
     */
    @RequestMapping("/login")
    public String login(){
        return "login";
    }
    /**
     * 404页面
     */
    @RequestMapping("/404")
    public String err(){
        return "404";
    }

    /**
     * 管理员登陆动作
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public Result doLogin(HttpServletRequest request,AdminUser adminUser){
        Result result = CaptchaUtil.checkCode( request, adminUser.getCode());
        if(ResultUtil.ERROR == result.getCode()){
          return result;
        }
        result = adminService.login(adminUser);
        if(ResultUtil.SUCCESS == result.getCode()){
            SessionUtil.setAdminUser(request,adminUser);
        }
        return result;
    }
    @RequestMapping(value = "/captcha", method = RequestMethod.GET)
    @ResponseBody
    public void captcha(HttpServletRequest request, HttpServletResponse response)
    {
        try {
            CaptchaUtil.outputCaptcha(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
